package com.firewolf.vue.verify;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 作者：刘兴
 * 时间:19/3/6
 **/
@Component
public class ImageCodeVerifyFilter extends OncePerRequestFilter {

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        if ("/mylogin".equals(request.getRequestURI()) && "post".equalsIgnoreCase(request.getMethod())) {

            try {
                valiadteImageCode(request);
            } catch (AuthenticationException e) {
                authenticationFailureHandler.onAuthenticationFailure(request, response, e);
            }

        }

        filterChain.doFilter(request, response);
    }

    private void valiadteImageCode(HttpServletRequest request) throws AuthenticationException {

        //验证验证码
        String verifycode = request.getParameter("verifycode");
        if (StringUtils.isBlank(verifycode)) {
            throw  new ImageCodeVerifyException("please input image code");
        }


        Object attribute = request.getSession().getAttribute("IMAGE_CODE");
        if (attribute == null) {
            throw  new ImageCodeVerifyException("there is no image code");
        }

        ImageCode imageCode = (ImageCode) attribute;

        if(!imageCode.isEffective()){
            throw  new ImageCodeVerifyException("image code time out");
        }

        if (!StringUtils.equalsIgnoreCase(verifycode, imageCode.getCode())) {
            throw  new ImageCodeVerifyException("image code is error");
        }
    }
}
